import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { history } from 'umi';
import { Table, Button, Tabs, message, Spin, Form, Tooltip, Space } from 'antd';
import _ from 'lodash';
import SupplierModal from './SupplierModal';
import {
  CQXG_STATE,
  DB_STATE,
  InceptionData,
  LB_STATE,
  LRKPB_STATE,
  SHTG_CHECKSTATE,
  SHTH_CHECKSTATE,
  formatDecimal,
  returnDelIds,
  setTableRowClassName,
} from '../common/Format';
import { getSupplierTableColumns } from '../mconfig';
import { DiffOutlined, CheckCircleOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { Descriptions, useDescriptions } from '@/components/Descriptions';
import { SourceUpdateContext } from '../common/UpdateContext';
// import { UploadFormCommon } from '../../Acomponents/UploadForm';
import {
  addSupplierOneSerivice,
  applyBidService,
  editSupplierOneSerivice,
  editSupplierTwoServices,
  findSourceInviteService,
  getSupplierOneSerivice,
  sourceUpdateStateService,
} from '../services/UpdateService';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { IUpdateEnum } from '../common/UpdateReducer';
import { downloadTemplate, getFileNameNotType, getTenantID, splitFileUrl } from '@/utils';
import MyIcon from '@/components/MyIcon';
import { sortCreateTimeData } from '../../Acommon';
import Cls from 'classnames';
import { UploadFormCommon } from '@/components/UploadForm';
import { ILoadMapTypeAll } from '@/common';

/**
 * @UpdateSourceSupplierView 供应商报价组件
 * @returns
 */
const UpdateSourceSupplierView = () => {
  const { Source_CurrentStep, Invite_PackList, Source_Invite, curRes, locationProps, dispatch } = useContext(SourceUpdateContext);
  const { type, info } = locationProps?.state || {};
  const [allList, setAllList] = useState<Record<string, any>[]>([]); // 数据总集合
  const [PackIndex, setPackIndex] = useState<number>(0); // 保存选择标包的下标
  const [selectKey, setSelectKey] = useState<string>(); //tab选择项
  const [speForm] = Form.useForm(); // 表单实例
  const [tendersReluseBool, setTendersReluseBool] = useState<boolean>(true); // 保存招标结果是否正确
  const [supplierState, setSupplierState] = useState<Record<string, any>>({ isShow: false, index: 0 }); // 是否展示选择供应商弹窗
  const [isDelModal, setIsDelModal] = useState<Record<string, any>>({}); // 显示删除供应商弹窗
  const [isUsModal, setIsUsModal] = useState<Record<string, any>>({}); // 显示实施状态
  const [isOpen, setIsOpen] = useState<boolean>(false); //是否可以填写开评标-根据接口查看澄清判断

  // <<<==============================Services================================>>>START

  /** 添加接口 */
  const { addSupplierOneRun, addSupplierOneLoading } = addSupplierOneSerivice((res, isTwoAdd) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      getPackListServices();
      let { isAdd } = isTwoAdd;
      if (isAdd) {
        getSupplierOneRun({ packID: res?.obj }, isAdd);
      }
    } else {
      message.error(res?.msg);
    }
  });

  /** 详情接口 */
  const { getSupplierOneRun, getSupplierOneLoading } = getSupplierOneSerivice((res, flag) => {
    if (res?.msgFlag) {
      let { rows } = res;

      /** 保存定标ID 这个在定标页面用来判断是否有定标详情 */
      if (rows?.length > 0) {
        let idsObj = rows?.find((item: any) => item.calibrateID);
        dispatch({ type: IUpdateEnum.Set_Calibrate_Id, payload: idsObj?.calibrateID });
      }

      // 字段替换
      rows?.forEach((item) => {
        item.fullName = item?.supplyName; // 供应商名称/企业名称

        // 下层的值拿到上层
        if (item?.mpurchaseSourcePrepare) {
          item.quotationType = item?.mpurchaseSourcePrepare?.quotationType;
          item.sumInTaxText = item?.mpurchaseSourcePrepare?.sumInTaxText;
          item.sumInTax = item?.mpurchaseSourcePrepare?.sumInTax;
          item.priceScore = item?.mpurchaseSourcePrepare?.priceScore;
          item.techScore = item?.mpurchaseSourcePrepare?.techScore;
          item.busiScore = item?.mpurchaseSourcePrepare?.busiScore;
          item.sumScore = item?.mpurchaseSourcePrepare?.sumScore;
          item.bidFileURL = item?.mpurchaseSourcePrepare?.bidFileURL;
          item.reviewReportURL = item?.mpurchaseSourcePrepare?.reviewReportURL;
          item.questioningMaterialsURL = item?.mpurchaseSourcePrepare?.questioningMaterialsURL;
          item.complaintMaterialsURL = item?.mpurchaseSourcePrepare?.complaintMaterialsURL;
          item.selectFlag = item?.mpurchaseSourcePrepare?.selectFlag;
        }
      });

      let new_allList = _?.cloneDeep(allList);
      let packIndex = new_allList?.findIndex((item) => item?.packID == selectKey);
      // 功能标识
      if (rows?.length == 0) {
        new_allList[packIndex].isAdd = true;
        if (new_allList[packIndex].nowMpurchaseSourceSupplierList?.length === 0) {
          new_allList[packIndex].nowMpurchaseSourceSupplierList = [];
        }
      } else {
        new_allList[packIndex].isAdd = false;
        new_allList[packIndex].mpurchaseSourceSupplierList = [...rows]; // 源数据
        if (new_allList[packIndex].nowMpurchaseSourceSupplierList?.length === 0) {
          new_allList[packIndex].nowMpurchaseSourceSupplierList = [...rows];
        }

        setFieldsValue({
          bidResult: Number(rows?.[0]?.bidResult),
          evalURL: rows?.[0]?.evalURL,
        });
      }

      // 单独判断，是不是需要重新更新展示的数组
      if (flag) new_allList[packIndex].nowMpurchaseSourceSupplierList = [...rows];

      setTendersReluseBool(Boolean(allList?.[PackIndex]?.bidResult));
      setAllList(new_allList);
    }
  }, curRes);

  /** 编辑1号接口 - 【主用删除供应商功能】 */
  const { editSupplierOneRun, editSupplierOneLoading } = editSupplierOneSerivice((res, ParamsObj) => {
    if (res?.msgFlag) {
      editSupplierTwoRun({ ...ParamsObj });
    }
  });

  /** 编辑2号接口 - 【主用编辑供应商报价】 */
  const { editSupplierTwoRun, editSupplierTwoLoading } = editSupplierTwoServices((res, flag) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      getSupplierOneRun({ packID: res?.obj }, flag);
    }
  });

  const [submitFalg, setSubmitFalg] = useState(false);

  /** 修改实施状态接口 */
  const { applyBidRun, applyBidLoading } = applyBidService((res) => {
    if (res?.msgFlag) {
      setIsUsModal({}); // 关闭弹窗
      getPackListServices();
      // message.success(res?.msg);
      if (submitFalg) {
        history.push({
          pathname: '/sourceController/manage',
          state: {
            delRouterNameSource: history.location.pathname,
          },
        });
      }
    } else {
      message.error(res?.msg);
    }
  });

  /** 获取标包数据接口 */
  const { findSourceInviteRun, findSourceInviteLoading } = findSourceInviteService();

  /** 判断是否可以填写开评标 */
  const { sourceUpdateStateRun, sourceUpdateStateLoading } = sourceUpdateStateService((res) => {
    setIsOpen(res?.msgFlag);
    if (!res?.msgFlag && Source_CurrentStep == 3) message?.warn(res?.msg);
    if (selectKey) getSupplierOneRun({ packID: selectKey }, false);
  });

  // <<<==============================Services================================>>>START

  // <<<==============================Function================================>>>START

  /** 是否显示操作按钮 */
  const isShowOpenBtn = useMemo(() => {
    if (type == 'detail') return false;
    if (!Invite_PackList || !Invite_PackList?.length) return false;
    if (allList?.[PackIndex]?.sourceState == DB_STATE() || allList?.[PackIndex]?.sourceState == LB_STATE()) return false;
    if (
      isOpen &&
      curRes?.['/purchaseSourceSupplierController/add'] &&
      curRes?.['/purchaseSourceSupplierController/editSourceSupplier'] &&
      curRes?.['/purchaseSourceSupplierController/addSourceSupplier']
    ) {
      return true;
    }
    return false;
  }, [Invite_PackList, PackIndex, curRes, isOpen, type, allList]);

  /** 抛出事件 */
  const methods = { setValues: (value: Record<string, any>[]) => {} };

  /** 招标是否成功 */
  const changeBidding = (value: number) => {
    let new_allList = _?.cloneDeep(allList);
    new_allList[PackIndex].bidResult = value;
    setAllList(new_allList);
    if (value) {
      setTendersReluseBool(true);
    } else {
      setTendersReluseBool(false);
    }
  };

  /** 表格 */
  const [config, { setFieldsValue, validateFields }] = useDescriptions({
    name: 'source-supplier',
    schemas: [
      {
        label: '一、开评标结果',
        field: 'Title',
        component: 'Title',
      },
      {
        label: '招标是否成功',
        field: 'bidResult',
        component: 'Render',
        colSpan: 1,
        slotRender: (text) => {
          if (isOpen && (allList?.[PackIndex]?.sourceState == CQXG_STATE() || allList?.[PackIndex]?.sourceState == LRKPB_STATE())) {
            return (
              <TagSelect
                colSpan={24}
                formLabel={''}
                formName={'bidResult'}
                onChange={changeBidding}
                radioDisabled={!isShowOpenBtn}
                defalultKeys={Number(allList?.[PackIndex]?.bidResult)}
                radioList={[
                  {
                    value: 1,
                    name: '成功',
                  },
                  {
                    value: 0,
                    name: '失败',
                  },
                ]}
              />
            );
          } else {
            return <span style={{ marginLeft: '8px' }}>{Number(text) == 1 ? '成功' : Number(text) == 0 ? '失败' : '--'}</span>;
          }
        },
      },
      {
        label: '评标报告',
        field: 'evalURL',
        component: 'Render',
        colSpan: 1,
        required: true,
        slotRender: (text, record) => {
          if (
            (curRes?.['/purchaseSourceSupplierController/addSourceSupplier'] || curRes?.['/purchaseSourceSupplierController/editSourceSupplier']) &&
            type != 'detail' &&
            (allList?.[PackIndex]?.sourceState == LRKPB_STATE() || allList?.[PackIndex]?.sourceState == CQXG_STATE()) &&
            isOpen
          ) {
            return (
              <div>
                <UploadFormCommon
                  form={speForm}
                  fileFormName={'evalURL'}
                  spanCol={24}
                  inRowProportion={24}
                  name={'attachFile'}
                  required={true}
                  accept={'.doc|.docx|.pdf'}
                  url={'/purchaseSourcePrepareController/uploadFile'}
                  downloadUrl={'/purchaseSourcePrepareController/downloadFile'}
                  fileFormDelName={'delLicenceUrl'}
                  delFunc={() => {
                    let new_allList = _?.cloneDeep(allList);
                    new_allList[PackIndex].evalURL = null;
                    setAllList(new_allList);
                  }}
                  uploadSuccessCallback={(url) => {
                    let new_allList = _?.cloneDeep(allList);
                    setFieldsValue({ evalURL: url });
                    new_allList[PackIndex].evalURL = url;
                    setAllList(new_allList);
                  }}
                  maxFile={1}
                  defaultFiles={allList[PackIndex].evalURL || undefined}
                  fieldBusiPath={'purchase/prepare'}
                  // isShowUploadBtn={true}
                >
                  上传
                </UploadFormCommon>
              </div>
            );
          } else {
            return (
              <div style={{ marginLeft: 8 }}>
                {allList[PackIndex]?.evalURL
                  ? splitFileUrl(allList[PackIndex]?.evalURL)?.map((e) => {
                      return (
                        <Tooltip title={e.attachName} key={new Date().getTime() * 545215252 + e?.attachName}>
                          <a
                            onClick={() => {
                              message.success('下载中，请稍后...');
                              downloadTemplate('/purchaseSourcePrepareController/downloadFile', e?.attachName, e?.attachUrl, () => {});
                            }}
                          >
                            <MyIcon type="icon-file-text-fill" />
                            &nbsp;
                            {getFileNameNotType(e.attachName, 8)}
                          </a>
                        </Tooltip>
                      );
                    })
                  : '--'}
              </div>
            );
          }
        },
      },
    ],
  });

  /** 保存选中企业/供应商 */
  const onSaveSupplier = (value: Record<string, any>[]) => {
    if (!value || !value?.length) return;

    if (supplierState?.type == 'checkBox') {
      // 多选
      let new_allList = _?.cloneDeep(allList);
      let data = new_allList[PackIndex]?.nowMpurchaseSourceSupplierList;
      let newarr: Record<string, any>[] = [];
      value?.forEach((item) => {
        newarr?.push({
          ...InceptionData(),
          fullName: item?.fullName, // 供应商名称
          supplyName: item?.fullName, // 供应商名称
          creditID: item?.creditID, // 统一社会信用代码(同步)
          representative: item?.representative, // 法人代表
          contactName: item?.contactName, // 联系人姓名(同步)
          contactMobile: item?.contactMobile, // 联系方式(同步)
          contactAddress: item?.contactAddress, // 联系地址(同步)
          contactEmail: item?.contactEmail, // 电子邮箱(同步)
          supplierID: item?.id, // 供应商id
        });
      });
      new_allList[PackIndex].nowMpurchaseSourceSupplierList = [...data, ...newarr];
      setAllList(new_allList);
    } else if (supplierState?.type == 'radio') {
      // 单选
      const resObj = value?.[0];
      const { index } = supplierState;
      let new_allList = _?.cloneDeep(allList);
      const data = new_allList[PackIndex]?.nowMpurchaseSourceSupplierList;
      data[index].fullName = resObj?.fullName; // 供应商名称
      data[index].supplyName = resObj?.fullName; // 供应商名称
      data[index].creditID = resObj?.creditID; // 统一社会信用代码(同步)
      data[index].representative = resObj?.representative; // 法人代表
      data[index].contactName = resObj?.contactName; // 联系人姓名(同步)
      data[index].contactMobile = resObj?.contactMobile; // 联系方式(同步)
      data[index].contactAddress = resObj?.contactAddress; // 联系地址(同步)
      data[index].contactEmail = resObj?.contactEmail; // 电子邮箱(同步)
      data[index].supplierID = resObj?.id; // 供应商id
      setAllList(new_allList);
    }
  };

  /** 框架协议 && 便捷框架协议 */
  const filterList = ['100122011006', '100122011010'];

  /** 推荐中标人【只选中一个】 */
  const changeBidder = (value: boolean, index: number) => {
    let new_allList = _?.cloneDeep(allList);
    let data = new_allList[PackIndex]?.nowMpurchaseSourceSupplierList;
    // 除了以上两种不用互斥，其他互斥
    if (!filterList.includes(Source_Invite?.procureReal)) {
      data?.forEach((item, idx) => {
        item.selectFlag = 0;
        if (index == idx) {
          item.selectFlag = Number(value);
        }
      });
      setAllList(new_allList);
    } else {
      //框架不互斥
      data?.forEach((item, idx) => {
        if (index == idx) {
          item.selectFlag = Number(value);
        }
      });
      setAllList(new_allList);
    }
  };

  /** 左侧tab切换 */
  const changeTabs = useCallback(
    (value) => {
      setSelectKey(value);
      let page = Invite_PackList?.findIndex((item) => item?.id == value);
      setPackIndex(page);
      setFieldsValue({
        bidResult: Number(allList?.[page]?.bidResult),
        evalURL: allList?.[page]?.evalURL,
      });
      setTendersReluseBool(Boolean(allList?.[page]?.bidResult));
    },
    [allList, PackIndex],
  );

  /** columns的数据改变方法 */
  const onEditTable = (arg) => {
    const { value, key, type, record, index } = arg;

    let new_allList = _?.cloneDeep(allList);
    let data = new_allList[PackIndex]?.nowMpurchaseSourceSupplierList;

    /** 报价 */
    if (key == 'sumInTax') {
      if (type == 'InputNumber') {
        data[index].quotationType = 0;
        data[index].sumInTaxText = null;
        data[index].sumInTax = value;
      } else if (type == 'InputTextArea') {
        data[index].quotationType = 1;
        data[index].sumInTax = allList[0]?.expectSum;
        data[index].sumInTaxText = value;
      }
    }

    /** 上传文件 */
    if (type == 'UploadFormCommon') {
      if (key == 'reviewReportURL') {
        data[index].reviewReportURL = value;
      }
      if (key == 'bidFileURL') {
        data[index].bidFileURL = value;
      }
      if (key == 'questioningMaterialsURL') {
        data[index].questioningMaterialsURL = value;
      }
      if (key == 'complaintMaterialsURL') {
        data[index].complaintMaterialsURL = value;
      }
    }

    /** 联合成员 */
    if (type == 'Input') {
      if (key == 'complexNames') {
        data[index].complexNames = value;
      }
    }

    /** 是否联合 */
    if (type == 'Check') {
      if (key == 'complexFlag') {
        data[index].complexFlag = value;
      }
    }

    /** 报价类型 */
    if (type == 'Select') {
      if (key == 'quotationType') {
        data[index].quotationType = value;
        if (value === 0) {
          data[index].sumInTax = null;
        } else {
          data[index].sumInTax = null;
        }
      }
    }

    setAllList(new_allList);
  };

  /** 添加一行数据 */
  const addDataSource = (index) => setSupplierState({ isShow: true, index: 0, type: 'checkBox' });

  /** 删除一行数据 */
  const deleteDataSource = (index: number, record: Record<string, any>) => {
    if (record?.id || record?.fullName) {
      setIsDelModal({ isShow: true, index, record });
    } else {
      let new_allList = _?.cloneDeep(allList);
      new_allList[PackIndex]?.nowMpurchaseSourceSupplierList?.splice(index, 1);
      setAllList(new_allList);
    }
  };

  /** 暂存按钮事件 */
  const onSubmit = async () => {
    let new_allList = _?.cloneDeep(allList);
    let packData = new_allList[PackIndex];

    if (!packData?.nowMpurchaseSourceSupplierList?.length) {
      message?.warn('请填写供应商报价信息！');
      return new Promise((res, rej) => rej);
    }

    await validateFields();

    let flag = true;
    packData?.nowMpurchaseSourceSupplierList?.forEach((item) => {
      // 报价
      if (!item?.sumInTax || (item?.quotationType === 1 && !item?.sumInTaxText) || (item?.quotationType === 0 && !item?.sumInTax)) {
        flag = false;
        return;
      }
    });
    if (!flag) return message?.warn('请填写完整的报价信息，值不能为空！');

    let addList: Record<string, any>[] = []; // 需要添加的数据 【如果是新数据，那么这些数据都不存在id，也就还会再addList中】
    let editList: Record<string, any>[] = []; // 需要编辑的数据

    // 遍历当前标包显示的数据
    packData?.nowMpurchaseSourceSupplierList?.forEach((item) => {
      if (item?.id) {
        editList?.push({
          id: item?.mpurchaseSourcePrepare?.id,
          sumInTax: item?.sumInTax, // 报价含税总额(含税价=不含税价×（1+税率）) || 预算
          sumInTaxText: item?.sumInTaxText, // 如果是单价的话，可以填写文本内容
          quotationType: item?.quotationType || 0, //报价类型
          priceScore: item?.priceScore, //价格得分
          techScore: item?.techScore, //技术得分
          busiScore: item?.busiScore, //商务得分
          sumScore: item?.sumScore, //总得分
          bidFileURL: item?.bidFileURL, //投标文件
          reviewReportURL: item?.reviewReportURL, //添加/编辑增加评审报告
          complaintMaterialsURL: item?.complaintMaterialsURL, //投诉及处理材料
          questioningMaterialsURL: item?.questioningMaterialsURL, //质疑及处理材料
          selectFlag: item?.selectFlag, //推荐中标人
          versionNum: item?.versionNum, //版本号
          expectSum: item?.expectSum, //预估总价
        });
      } else {
        addList?.push({
          supplierID: item?.supplierID, //供应商id
          suggestInfo: item?.suggestInfo, //推荐理由
          creditID: item?.creditID, //统一社会信用代码(同步)
          supplyName: item?.supplyName, //供应商名称(同步)
          representative: item?.representative, //法人代表
          contactName: item?.contactName, //联系人姓名(同步)
          contactMobile: item?.contactMobile, //联系方式(同步)
          contactAddress: item?.contactAddress, //联系地址(同步)
          contactEmail: item?.contactEmail, //电子邮箱(同步)
          complexFlag: item?.complexFlag, //是否联合体
          complexNames: item?.complexNames, //联合体成员
          expectSum: item?.expectSum, //预估总价
          //这个对象里面是供应商的报价信息
          mpurchaseSourcePrepare: {
            sumInTax: item?.sumInTax, // 报价含税总额(含税价=不含税价×（1+税率）) || 预算
            sumInTaxText: item?.sumInTaxText, // 如果是单价的话，可以填写文本内容
            quotationType: item?.quotationType, //报价类型
            priceScore: item?.priceScore, //价格得分
            techScore: item?.techScore, //技术得分
            busiScore: item?.busiScore, //商务得分
            sumScore: item?.sumScore, //总得分
            bidFileURL: item?.bidFileURL, //投标文件
            reviewReportURL: item?.reviewReportURL, //添加/编辑增加评审报告
            complaintMaterialsURL: item?.complaintMaterialsURL, //投诉及处理材料
            questioningMaterialsURL: item?.questioningMaterialsURL, //质疑及处理材料
            selectFlag: item?.selectFlag, //推荐中标人
          },
        });
      }
    });

    // 判断是否是纯新增，这个在详情接口返回是不是空数组给的属性，如果详情返回的是空数组，则 isAdd = true
    if (packData?.isAdd) {
      let ParamsObj: Record<string, any> = {
        sourceID: packData?.sourceID,
        packID: packData?.packID,
        expectSum: packData?.expectSum,
        bidResult: packData?.bidResult,
        evalURL: packData?.evalURL,
        mpurchaseSourceSupplierList: addList,
      };
      await addSupplierOneRun(ParamsObj, { isAdd: true, addData: ParamsObj });
    } else {
      let ParamsObj: Record<string, any> = {
        sourceID: packData?.sourceID,
        packID: packData?.packID,
        expectSum: packData?.expectSum,
        bidResult: packData?.bidResult,
        evalURL: packData?.evalURL,
        mpurchaseSourcePrepareList: editList,
      };

      const delIds = returnDelIds({
        oldData: packData?.mpurchaseSourceSupplierList,
        newData: packData?.nowMpurchaseSourceSupplierList,
        screen: 'id',
        back: 'id',
      });

      if (addList?.length) {
        // 掺杂新增的编辑
        let addParams = {
          sourceID: packData?.sourceID,
          packID: packData?.packID,
          expectSum: packData?.expectSum,
          bidResult: packData?.bidResult,
          evalURL: packData?.evalURL,
          mpurchaseSourceSupplierList: addList,
        };

        if (editList?.length) {
          if (delIds) {
            await editSupplierOneRun({ delIds }, ParamsObj).then(async () => {
              await addSupplierOneRun(addParams, { isAdd: false });
            });
            return;
          }
          await addSupplierOneRun(addParams, { isAdd: false });
        } else {
          if (delIds) {
            await editSupplierOneRun({ delIds }, ParamsObj).then(async () => {
              await addSupplierOneRun(addParams, { isAdd: false });
            });
            return;
          }
          await addSupplierOneRun(addParams, { isAdd: true });
        }
      } else {
        // 正常的编辑
        // 如果有需要删除的供应商，直接在调完删除供应商的接口后，调修改报价接口
        if (delIds) {
          await editSupplierOneRun({ delIds }, ParamsObj);
        } else {
          if (ParamsObj?.mpurchaseSourcePrepareList?.length != 0) {
            await editSupplierTwoRun(ParamsObj);
          }
        }
      }
    }
    await applyBidRun({ ids: allList?.[PackIndex]?.sourceID, state: LRKPB_STATE() });
  };

  /** 更新标包详情方法 */
  const getPackListServices = async () => {
    const { obj } = await findSourceInviteRun({
      id: Source_Invite?.id,
      noticeCode: Source_Invite?.noticeCode,
      applyID: Source_Invite?.applyID,
    });
    obj.mpurchaseSourceList = sortCreateTimeData(obj.mpurchaseSourceList); // 根据创建时间排序
    dispatch({ type: IUpdateEnum.Set_Invite_PackList, payload: obj.mpurchaseSourceList }); // 派发更新
  };

  /** 初始化仓库 */
  useEffect(() => {
    if (Invite_PackList?.length && Source_Invite?.id) {
      const n_allList = Invite_PackList?.map((item, index) => {
        let bidResult = item?.bidResult === null || item?.bidResult === undefined ? 1 : item?.bidResult;
        let record = {
          packID: item?.id,
          packName: item?.packName,
          packCode: item?.packCode,
          sourceID: item?.id,
          expectSum: item?.expectSum,
          sourceState: item?.state, //实施状态[按钮判断需要用]
          bidResult: bidResult, // 当前标包的初始 - 招标结果[控制下方表格是否显示]
          evalURL: item?.evalURL, // 评标结果[文件]
          mpurchaseSourceSupplierList: [],
          nowMpurchaseSourceSupplierList: [],
        };

        if (index == 0) {
          // 第一次
          setFieldsValue({ bidResult, evalURL: item?.evalURL });
          setTendersReluseBool(Boolean(bidResult));
        }

        return record;
      });
      setAllList(n_allList);
    }
  }, [Invite_PackList, Source_Invite]);

  /** 初始化Tab切换标识 */
  useEffect(() => {
    if (Invite_PackList?.[0]?.id) {
      const selectedInfo = Invite_PackList?.find((item) => item?.id === info?.id);
      const indexPage = Invite_PackList?.findIndex((item) => item?.id === info?.id);
      const result = Invite_PackList?.find((item) => item?.id == selectKey);
      if (!result) {
        /** 采购实施管理页点击开标按钮或者查看详情进来后默认选中对应的包-左侧tab栏 */
        if (selectedInfo?.id) {
          setPackIndex(indexPage || 0);
          setSelectKey(selectedInfo?.id);
          return;
        }
        setSelectKey(Invite_PackList?.[0]?.id);
      } else {
        setSelectKey(result?.id);
      }
    }
  }, [Invite_PackList]);

  /** 监听Tab切换 */
  useEffect(() => {
    if (selectKey) {
      sourceUpdateStateRun({
        id: selectKey,
        applyID: Source_Invite?.applyID,
        expertState: `${getTenantID()}${ILoadMapTypeAll.EXPERT_BUSINESSTYPE}1002,${getTenantID()}${ILoadMapTypeAll.EXPERT_BUSINESSTYPE}1003`,
      });
    }
  }, [selectKey, Invite_PackList, Source_CurrentStep]);

  // <<<==============================Function================================>>>END

  /** 主体 */
  const container = () => {
    return (
      <div className={'source-supplier'}>
        <Spin
          spinning={
            addSupplierOneLoading ||
            getSupplierOneLoading ||
            editSupplierOneLoading ||
            editSupplierTwoLoading ||
            findSourceInviteLoading ||
            applyBidLoading ||
            sourceUpdateStateLoading
          }
        >
          <div className={'source-supplier-tabs'}>
            {Invite_PackList?.length > 0 && (
              <div className={Cls('source-experts-tabs', 'source-tabs-color')}>
                <Tabs
                  tabPosition={'left'}
                  items={Invite_PackList.map((item, i) => {
                    return { label: item?.packCode, key: item?.id };
                  })}
                  onChange={(value) => changeTabs(value)}
                  activeKey={selectKey}
                />
              </div>
            )}
          </div>
          <ScrollBarLayout>
            <div className={'source-supplier-desc'}>
              <Descriptions config={config} />
              <div className={'source-supplier-row'}>
                <div className={'source-supplier-item-title'}>二、供应商报价</div>
                <div className={'list-table'}>
                  <Table
                    size="small"
                    bordered
                    rowKey={'index'}
                    scroll={{ x: 1000 }}
                    rowClassName={setTableRowClassName}
                    pagination={false}
                    columns={getSupplierTableColumns({
                      onAdd: addDataSource,
                      onDelete: deleteDataSource,
                      openSupplier: (index: number) => setSupplierState({ isShow: true, index, type: 'radio' }),
                      changeBidder,
                      onEditTable,
                      SourceState: allList?.[PackIndex]?.sourceState,
                      isShowOpenBtn,
                    })}
                    dataSource={allList?.[PackIndex]?.nowMpurchaseSourceSupplierList || []}
                  />
                </div>
              </div>
            </div>
          </ScrollBarLayout>

          {/* 选择供应商 */}
          {supplierState.isShow && (
            <SupplierModal
              dataList={allList?.[PackIndex]?.nowMpurchaseSourceSupplierList || []}
              onSave={(value: Record<string, any>[]) => onSaveSupplier(value)}
              onClose={() => setSupplierState({ isShow: false, index: 0 })}
              selectType={supplierState?.type}
            />
          )}

          {/* 删除供应商报价弹窗 */}
          {isDelModal?.isShow && (
            <TipsErrorModalNew
              modalLoading={false}
              modalTip={<>确认删除：【{isDelModal?.record?.fullName || '--'}】的供应商报价！</>}
              onClose={() => setIsDelModal({})}
              modalOnOK={() => {
                let new_allList = _?.cloneDeep(allList);
                new_allList[PackIndex]?.nowMpurchaseSourceSupplierList?.splice(isDelModal?.index, 1);
                setAllList(new_allList);
              }}
            />
          )}

          {/* 修改实施状态弹窗 */}
          {isUsModal?.isShow && (
            <TipsErrorModalNew
              modalLoading={findSourceInviteLoading || applyBidLoading}
              onClose={() => {
                setIsUsModal({});
              }}
              modalOnOK={() => {
                setSubmitFalg(true);
                if (allList?.[PackIndex]?.bidResult === 0) {
                  applyBidRun({
                    ids: allList?.[PackIndex]?.sourceID,
                    state: LB_STATE(),
                  });
                } else if (allList?.[PackIndex]?.bidResult === 1) {
                  applyBidRun({
                    ids: allList?.[PackIndex]?.sourceID,
                    state: DB_STATE(),
                  });
                }
              }}
              modalTip={<>请确认提交【{isUsModal?.packList?.packCode || '--'}】的开评标信息！</>}
            />
          )}
        </Spin>
      </div>
    );
  };

  /** 底部操作按钮 */
  const btnFooter = () => {
    return (
      <Space>
        {curRes?.['/purchaseSourceSupplierController/addSourceSupplier'] &&
          curRes?.['/purchaseSourceSupplierController/editSourceSupplier'] &&
          type != 'detail' &&
          (allList?.[PackIndex]?.sourceState == LRKPB_STATE() || allList?.[PackIndex]?.sourceState == CQXG_STATE()) &&
          isOpen && (
            <Button type="primary" onClick={onSubmit}>
              暂存
            </Button>
          )}

        {
          // curRes?.['/purchaseSourceController/editState'] &&
          // allList?.[PackIndex]?.mpurchaseSourceSupplierList?.length != 0 && // 说明详情有数据
          // allList?.[PackIndex]?.sourceState == LRKPB_STATE() &&
          // type != 'detail' &&
          // isOpen &&

          curRes?.['/purchaseSourceSupplierController/addSourceSupplier'] &&
            curRes?.['/purchaseSourceSupplierController/editSourceSupplier'] &&
            curRes?.['/purchaseSourceController/editState'] && //提交需要比暂存多个修改状态的权限
            type != 'detail' &&
            (allList?.[PackIndex]?.sourceState == LRKPB_STATE() || allList?.[PackIndex]?.sourceState == CQXG_STATE()) &&
            isOpen && (
              <Button
                type={'primary'}
                onClick={async () => {
                  await onSubmit();
                  setIsUsModal({
                    isShow: true,
                    packList: allList?.[PackIndex],
                  });
                }}
              >
                提交
              </Button>
            )
        }
      </Space>
    );
  };

  return {
    UpdateSourceSupplier: container,
    SourceSupplierFooter: btnFooter,
    SourceSupplierMethods: methods,
    tendersReluseBool,
  };
};

export default UpdateSourceSupplierView;
